#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import exceptions
import select

from logger import log, fytionException

class socketException(fytionException):
    """Socket error
    """

class tcpconn(object):
    
    _sock = None
    
    def __init__(self, host):
        try:
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error, e:
            raise socketException(e.errno, "Can not init socket.")
        
        (host,port) = tuple(host.split(":"))
        port = int(port)
        log("Trying to connect to %s:%d" %(host, port))
        # blocking mode
        self._sock.settimeout(None)
        try:
            self._sock.connect((host, port))
        except socket.error, e:
            self._sock.close()
            raise socketException(e.errno, "Can not connect to SIP proxy.")
    
    def close(self):
        self._sock.close()
    
    def send(self, data):
        #log(data)
        irdy, ordy, erdy = select.select([], [self._sock], [], 5.0)
        if not ordy:
            raise socketException(-20, "Cannot send data.")
        try:
            self._sock.sendall(data)
        except socket.error, e:
            self.close()
            raise socketException(-10, "Connection lost.")
    
    def recv(self, timeout = 0.0):
        if timeout == None:
            timeout = 10.0
        irdy, ordy, erdy = select.select([self._sock], [], [], timeout)
        if not irdy:
            return ''
        d = ''
        try:
            d = self._sock.recv(4096)
        except:
            pass
        if not d:
            self.close()
            raise socketException(-10, 'Connection lost.')
        #log(d)
        return d
    
    